<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在显示线程(主线程)中引入Babylon.js</title>
    <!--主线程要负责各个引擎之间的联系，负责dom渲染和事件，负责3D渲染，负责全局初始化-->
    <style>
        body{    margin: 0;    padding: 0;    border: 0;    text-align: center;    overflow: hidden;width: 100%;
            height: 100%;position: fixed;    font-family: verdana,arial,sans-serif;    touch-action: none;
            -ms-touch-action: none;font-size: 12px;min-width: 600px;}
        ul {    list-style: none;    margin: 0;    padding: 0;}
        li{    list-style: none;    margin: 0;    padding: 0;}
        ul li {    float: left;}
        button{    cursor: pointer;}
        a:link{    text-decoration: none;}
        #div_allbase{min-height: 500px;min-width: 750px;height: 100%;width:100%;position: relative;overflow-x:hidden;overflow-y: hidden;}
        #renderCanvas {    width: 100%;    height: 90%;    outline: none;}
        #fps {    position: absolute;    right: 20px;    top: 5em;    font-size: 20px;    color: white;/*帧数显示*/
            text-shadow: 2px 2px 0 black;}
        #div_control {    width: 100%;    height: 10%;    outline: none;position: relative}
        #div_left .btn_control{height: 23px;width: 23px;float: left;margin-top: 2px;margin-left: 2px}
        #div_right .btn_control{height: 23px;width: 23px;float: right;margin-top: 2px;margin-right: 2px}
    </style>
    <script src="babylon42.min.js"></script>
    <!--<script src="../../JS/MYLIB/newland.js"></script>-->
    <script src="newland.js"></script>
    <script src="One.js"></script>
    <script src="Dic.js"></script>
    <script src="VTools.js"></script>
    <script src="OneRender.js"></script>
    <script src="Control.js"></script>
</head>
<body>
<div id="div_allbase">
    <canvas id="renderCanvas"></canvas>
    <div id="fps" style="z-index: 302;"></div>
    <div id="div_control" >
        <div id="div_left" style="left:0px;bottom: 0px;position: absolute;height: 100%;width: 250px">
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
        </div>
        <div id="div_right" style="right:0px;bottom: 0px;position: absolute;height: 100%;width: 250px">
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
            <button class="btn_control"></button>
        </div>
        <div id="div_middle" style="right:250px;left:250px;height: 100%;position: absolute;text-align: center"></div>
    </div>
</div>
</body>
<script>
    //全局变量堆放区
    var VERSION=0.1,AUTHOR="1113908055@qq.com";

    var canvas=document.getElementById("renderCanvas");
    var divFps=document.getElementById("fps");
    var div_left=document.getElementById("div_left");
    var arr_btn_left=div_left.getElementsByTagName("button");
    var div_right=document.getElementById("div_right");
    var arr_btn_right=div_right.getElementsByTagName("button");
    var div_middle=document.getElementById("div_middle");

    var worker;

    var engine = new BABYLON.Engine(canvas, true);
    engine.displayLoadingUI();
    var gl=engine._gl;//决定在这里结合使用原生OpenGL和Babylon.js;
    var scene = new BABYLON.Scene(engine);
    //console.log("a"+new Date().getTime());//第一个script标签执行后第二个才会执行，但即使第一个报了错第二个仍会执行
    var obj_global={};
    var obj_mat={};
    var camera0,light0;
</script>
<script>
    //console.log("b"+new Date().getTime());
    window.onload=beforeInit;
    function beforeInit()
    {
        Init();
    }
    var obj_units={};//用id索引所有单位
    var obj_unitclassed={};//用class索引所有单位类型《-这个数据对象还是放在这里比较好，如果放在其他文件里则难以记住对象名！！
    var flag_runningstate="等待初始化";//系统总体运行状态（未用到）
    var count_init=2;
    var flag_autorun=false;//是否自动运行，默认非自动运行，点击一次“步进”按钮计算一次。
    function Init()
    {
        //initThem
        One.createRandomThem(obj_units,100,[-50,50],[-50,50]);//第一次实验只有一个地块
        //initMat
        var mat_alpha05=new BABYLON.StandardMaterial("mat_alpha05", scene);
        mat_alpha05.alpha=0.5;
        mat_alpha05.twoSidedLighting=true;
        mat_alpha05.backFaceCulling=false;
        mat_alpha05.freeze();
        obj_mat.mat_alpha05=mat_alpha05;

        var mat_red=new BABYLON.StandardMaterial("mat_red", scene);
        mat_red.diffuseColor=new BABYLON.Color3(1,0,0);
        mat_red.twoSidedLighting=true;
        mat_red.backFaceCulling=false;
        mat_red.freeze();
        obj_mat.mat_red=mat_red;
        var mat_green=new BABYLON.StandardMaterial("mat_green", scene);
        mat_green.diffuseColor=new BABYLON.Color3(0,1,0);
        mat_green.twoSidedLighting=true;
        mat_green.backFaceCulling=false;
        mat_green.freeze();
        obj_mat.mat_green=mat_green;
        var mat_blue=new BABYLON.StandardMaterial("mat_blue", scene);
        mat_blue.diffuseColor=new BABYLON.Color3(0,0,1);
        mat_blue.twoSidedLighting=true;
        mat_blue.backFaceCulling=false;
        mat_blue.freeze();
        obj_mat.mat_blue=mat_blue;

        //initWorker
        console.log("开始启动work线程");
        worker = new Worker("WORK/worker.js");
        //这里需要吧One整理为更易传播的对象？《-是的
        var obj_units0=One.obj2data(obj_units);
        worker.postMessage(JSON.stringify({type:"initWork",obj_units0:obj_units0}));
        worker.onmessage=function(e)
        {
            var obj_data=JSON.parse(e.data)
            if(obj_data.type=="consoleLog")
            {
                console.log(obj_data.text);
            }
            else if(obj_data.type=="consoleError")
            {
                console.error(obj_data.text);
            }
            else if(obj_data.type=="workInited")
            {//
                console.log("逻辑初始化完成");
                count_init--;
                if(count_init==0)
                {
                    flag_runningstate="初始化完成";
                }
            }
            else if(obj_data.type=="updateUnits")
            {
                var obj_units0=obj_data.obj_units0;
                for(var key in obj_units0)
                {
                    var obj0=obj_units0[key];//从Think线程传递过来的新状态
                    var obj=obj_units[key];
                    obj.表现进化力=obj0.表现进化力;
                    obj.本能进化力=obj0.本能进化力;
                    obj.探索=obj0.探索;
                    obj.认同=obj0.认同;
                    obj.对比=obj0.对比;
                    obj.pos=obj0.pos;
                    obj.inner=obj0.inner;
                    obj.outer=obj0.outer;
                    obj.radius=obj0.radius;
                    obj.view=obj0.view;
                    obj.antieducation=obj0.antieducation;
                    obj.sensitivity=obj0.sensitivity;
                    obj.lover=obj0.lover;
                    obj.influence=obj0.influence;
                    obj.arr_history.push(obj0);

                    var one=obj0;
                    obj.node.position.x=one.pos.x;
                    obj.node.position.z=one.pos.z;
                    obj.node.position.y=one.pos.y;
                    var mesh_cylinder=obj.mesh_cylinder;                    
                    mesh_cylinder.scaling.y=one.表现进化力/100;
                    mesh_cylinder.scaling.x=one.radius;
                    mesh_cylinder.scaling.z=one.radius;
                    //mesh_cylinder.position.y=mesh_cylinder.scaling.y

                    obj.mesh_red.scaling.y=one.探索/100;
                    obj.mesh_green.scaling.y=one.认同/100;
                    obj.mesh_blue.scaling.y=one.对比/100;
                    //mesh_blue.position.y=mesh_blue.scaling.y;
                    obj.mesh_green.position.y=one.对比/50//+mesh_green.scaling.y;
                    obj.mesh_red.position.y=one.对比/50+one.认同/50//+mesh_red.scaling.y;
                    obj.mesh_plane.position.y=one.对比/50+one.认同/50+one.探索/50+0.4;

                    if(obj.line_educationed)
                    {
                        obj.line_educationed.dispose();
                    }
                    if(obj.lover)
                    {
                        var p1=obj.pos;
                        var p2=obj_units0[obj.lover].pos;
                        var dis=vxz.distance(p1,p2);
                        var v1=new BABYLON.Vector3(p1.x,p1.y+obj.mesh_plane.position.y,p1.z);
                        var v2=new BABYLON.Vector3(p2.x,p2.y,p2.z);
                        obj.line_educationed=BABYLON.MeshBuilder.CreateLines("line_educationed_"+obj.id//CreateDashedLines
                        , {points:[v1,v2],updatable: false,colors:OneRender.lineColors});//instance:obj.line_educationed,,dashNb:dis
                    }
                    // else{
                    //     obj.line_educationed=BABYLON.MeshBuilder.CreateDashedLines("line_educationed_"+obj.id
                    //     , {updatable: true,instance:obj.line_educationed,points:[]});
                    // }
                }
                //renderMap();
                console.log("完成一次计算："+(new Date().getTime()));//obj_data.frameTime
            }

        }

        //initThemRender
        OneRender.init();//初始化四个源网格，其他都适用这些源网格的实例；
        for(var key in obj_units)
        {
            var unit=obj_units[key];
            OneRender.createOneMesh(unit);
        }

        //initScene
        {
            //三个参照物
            var mat_green = new BABYLON.StandardMaterial("mat_green", scene);
            mat_green.diffuseColor = new BABYLON.Color3(0, 1, 0);
            mat_green.freeze();
            var mesh_base = new BABYLON.MeshBuilder.CreateSphere("mesh_base", {diameter: 1}, scene);
            mesh_base.material = mat_green;
            mesh_base.position.x = 0;
            //mesh_base.renderingGroupId=2;
            //mesh_base.layerMask=2;
            var mesh_base1 = new BABYLON.MeshBuilder.CreateSphere("mesh_base1", {diameter: 1}, scene);
            mesh_base1.position.y = 10;
            mesh_base1.position.x = 0;
            mesh_base1.material = mat_green;
            //mesh_base1.renderingGroupId=2;
            //mesh_base1.layerMask=2;
            var mesh_base2 = new BABYLON.MeshBuilder.CreateSphere("mesh_base2", {diameter: 1}, scene);
            mesh_base2.position.y = -10;
            mesh_base2.position.x = 0;
            mesh_base2.material = mat_green;
            //mesh_base2.renderingGroupId=2;
            //光照
            light0 = new BABYLON.HemisphericLight("light0", new BABYLON.Vector3(0, 1, 0), scene);
            light0.diffuse = new BABYLON.Color3(1, 1, 1);//这道“颜色”是从上向下的，底部收到100%，侧方收到50%，顶部没有
            light0.specular = new BABYLON.Color3(0, 0, 0);
            light0.groundColor = new BABYLON.Color3(1, 1, 1);//这个与第一道正相反
            obj_global.light0 = light0;
            //相机
            camera0 = new BABYLON.UniversalCamera("FreeCamera", new BABYLON.Vector3(0, 10, -70), scene);//FreeCamera
            camera0.minZ = 0.001;
            camera0.attachControl(canvas, true);
            scene.activeCameras.push(camera0);
            obj_global.camera0 = camera0;
        }

        //initControl
        //引入自定义控制监听
        InitMouse();
        window.addEventListener("keydown", onKeyDown, false);//按键按下
        window.addEventListener("keyup", onKeyUp, false);//按键抬起
        MyBeforeRender();
        arr_btn_right[0].innerHTML="v";
        arr_btn_right[0].onpointerup=function(e){
            e.key="v";
            onKeyUp(e);
        }
        arr_btn_left[0].innerHTML="单";
        arr_btn_left[0].onpointerup=function(e){
            runOneStep();
        }

        //scene.debugLayer.show();
        // engine.runRenderLoop(function () {
        //     scene.render();
        // });
        //flag_runningstate="初始化完成";
        console.log("渲染初始化完成");
        count_init--;
        if(count_init==0)
        {
            flag_runningstate="初始化完成";
        }
        engine.hideLoadingUI();
    }
    window.addEventListener("resize", function () {
        engine.resize();
    });

    function runOneStep(){//遍历每个unit并决定它要做的事，runLoop也要调用这个方法，暂时把思考、行动、渲染放在同步的帧里，思考频率、移动速度、单位大小要相互和谐，以正常移动避免碰撞为标准
        worker.postMessage(JSON.stringify({type:"command",func:"runOneStep",obj_p:null}));
        
        // renderMap();//渲染
    }

    function runLoop(){
        worker.postMessage(JSON.stringify({type:"setValue",key:"flag_autorun",value:true}));
        //flag_autorun=true;
    }
    function stopRunLoop(){
        worker.postMessage(JSON.stringify({type:"setValue",key:"flag_autorun",value:false}));
        //flag_autorun=false;
    }
    //var lastframe=new Date().getTime();
    function Loop()
    {
        worker.postMessage(JSON.stringify({type:"command",func:"Loop",obj_p:null}));
        // if(flag_autorun)
        // {
        //     runOneStep();
        //     var thisframe=new Date().getTime();
        //     console.log(thisframe-lastframe,"red:"+obj_owners.red.countAlive,"blue:"+obj_owners.blue.countAlive);
        //     lastframe=thisframe;
        // }
        // window.requestAnimationFrame(function(){Loop()});
    }


</script>
</html>